package com.stephenone.customviewdemo

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

private val IMAGE_WIDTH = 200f.dp
private val IMAGE_PADDING = 20f.dp
private val RING_WIDTH = 6f.dp
private val XFERMODE = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

class AvatarView2(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawOval(
            IMAGE_PADDING,
            IMAGE_PADDING,
            IMAGE_PADDING + IMAGE_WIDTH,
            IMAGE_PADDING + IMAGE_WIDTH,
            paint
        )

        //离屏缓冲
        val count = canvas.saveLayer(
            IMAGE_PADDING,
            IMAGE_PADDING,
            IMAGE_PADDING + IMAGE_WIDTH,
            IMAGE_PADDING + IMAGE_WIDTH,
            paint
        )
        canvas.drawOval(
            IMAGE_PADDING + RING_WIDTH,
            IMAGE_PADDING + RING_WIDTH,
            IMAGE_PADDING + IMAGE_WIDTH - RING_WIDTH,
            IMAGE_PADDING + IMAGE_WIDTH - RING_WIDTH,
            paint
        )
        paint.xfermode = XFERMODE
        canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt() - RING_WIDTH.toInt()), IMAGE_PADDING + RING_WIDTH, IMAGE_PADDING + RING_WIDTH, paint)
        paint.xfermode = null
        canvas.restoreToCount(count)
    }

    private fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.mipmap.mr_white, options)
        options.inJustDecodeBounds = false
        options.inDensity = options.outWidth
        options.inTargetDensity = width
        return BitmapFactory.decodeResource(resources, R.mipmap.mr_white, options)
    }
}